﻿using Google.Protobuf.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

public class CommunityItem : MonoBehaviour
{
    public NetworkImage icon;
    public Text nameText;
    public GameObject manSign;
    public GameObject womanSign;
    public Text birthYear;
    public Text location;
    public Text edu;
    public Text job;
    public Text content;
    public Text likeNum;
    public Image likeImg;
    public Text commentNum;
    public Text timeText;
    public Text topic;
    public GameObject topicObj;
    public Text monthText;
    public Text dayText;
    public MomentPhotoItem[] photos;
    public GridLayoutGroup photoGrisGroup;


    UserMoment m_UserMoment;
    public UserMoment userMoment => m_UserMoment;

    public void Init(UserMoment userMoment)
    {
        m_UserMoment = userMoment;

        content.text = userMoment.moment.content;

        var miniUserInfo = userMoment.miniUserInfo;
        icon.Init(miniUserInfo.icon);

        nameText.text = miniUserInfo.name;
        manSign.SetActive(miniUserInfo.gender == Gender.man);
        manSign.SetActive(miniUserInfo.gender == Gender.woman);
        birthYear.text = (miniUserInfo.birthYear % 1900) + "年";
        location.text = miniUserInfo.locationCity;
        edu.text = DataString.GetEducationString(miniUserInfo.eduation);
        job.text = miniUserInfo.job;

        DateTime date = new DateTime();
        if (userMoment.moment.time > 0)
        {
            date = UnityFunctions.TimeStampSeconds2DateTime(userMoment.moment.time);
            if (monthText)
                monthText.text = date.Month + "月";
            if (dayText)
                dayText.text = date.Day.ToString();
        }
        else
        {
            if (monthText)
                monthText.gameObject.SetActive(false);
            if (dayText)
                dayText.gameObject.SetActive(false);
        }

        if (topic)
        {
            if (string.IsNullOrEmpty(userMoment.moment.topic))
            {
                if (topicObj)
                    topicObj.gameObject.SetActive(false);
                else
                    this.topic.transform.parent.gameObject.SetActive(false);
            }
            else
            {
                this.topic.text = "#" + userMoment.moment.topic;
            }
        }

        if (userMoment.moment == null)
        {
            GameDebug.LogError("userMoment.moment == null");
            return;
        }

        RefreshLike(userMoment.moment.likes);
        RefreshCommentCount();

        for (int i = 0; i < 9; i++)
        {
            if (userMoment.moment.texs == null || i >= userMoment.moment.texs.Length)
            {
                photos[i].gameObject.SetActive(false);
                continue;
            }

            var spr = userMoment.moment.texs[i];
            if (!string.IsNullOrEmpty(spr))
            {
                if (i == 0)
                    photos[i].Init(spr, RefreshPhotoItemsSizes);
                else
                    photos[i].Init(spr);
            }
            else
            {
                photos[i].gameObject.SetActive(false);
            }
        }
        //GameDebug.Log($"photo count:{userMoment.moment.texs?.Length}");


        RefreshTime();
    }

    void RefreshPhotoItemsSizes()
    {
        int photoCount = photos.All(e=>e.gameObject.activeSelf).AsEnumerable().Count();

        float photoSize = 280;
        if (photoCount <= 1)
        {
            photoSize = 800;
            var size = photos[0].SetImgSize(photoSize);
            //size = photos[0].networkPhoto.photo.rectTransform.sizeDelta;
            photoGrisGroup.cellSize = size;
           //GameDebug.LogError($"{photos[0]} size:{size}");
        }
        else if (photoCount <= 2)
        {
            photoSize = 450;
            var size = photos[0].SetImgSize(photoSize);
            photos[1].SetImgSize(photoSize);
            //photos[0].networkPhoto.photo.rectTransform.sizeDelta;
            photoGrisGroup.cellSize = size;
            //GameDebug.LogError($"{photos[0]} size:{size}");
        }
        else
        {
            photoSize = 280;
            this.photoGrisGroup.cellSize = new Vector2(photoSize, photoSize);
            for (int i = 0; i < photoCount; i++)
            {
                photos[i].SetImgSize(photoSize);
            }
        }
    }

    void OnEnable()
    {
        StartCoroutine(UnityFunctions.AdjustItemsLayout(transform));
    }


    void RefreshTime()
    {
        this.timeText.text = UnityFunctions.GetTimeElapsed(m_UserMoment.moment.time) + "前";
    }

    bool myLike;
    public void RefreshLike(List<long> likes)
    {
        if (likes != null)
        {
            likeNum.text = likes.Count.ToString();

            myLike = false;
            for (int i = 0; i < likes.Count; i++)
            {
                if (likes[i] == MGame.instance.MUser.id)
                {
                    myLike = true;
                    break;
                }
            }
            likeImg.gameObject.SetActive(myLike);
        }
        else
        {
            likeNum.text = "0";
            likeImg.gameObject.SetActive(false);
        }
    }

    void RefreshCommentCount()
    {
        if (this)
        {
            int commentCount = userMoment.moment.comments != null ? userMoment.moment.comments.Count : 0;
            commentNum.text = commentCount.ToString();
        }
    }

    public void OnClickShare()
    {
        GameDebug.Log("CommunityItem->OnClickShare");
    }
    public void OnClickLike()
    {
        bool likeOrNot = !myLike;
        RequestServerController.instance.ReqLikeMoment(MGame.instance.MUser.id, likeOrNot, this.m_UserMoment.userId, this.m_UserMoment.moment.momentId, (res) =>
        {
            if (likeOrNot)
                m_UserMoment.moment.AddLike(MGame.instance.MUser.id);
            else
                m_UserMoment.moment.RemoveLike(MGame.instance.MUser.id);
           
            RefreshLike(m_UserMoment.moment.likes);
        });
    }
    public void OnClickComment()
    {
        GameDebug.Log("CommunityItem->OnClickComment");

        var moment = GetComponentInParent<UIController>().ShowUI<MomentPanel>();
        moment.Init(m_UserMoment);
        moment.onLikesRefresh = () =>
        {
            if(this)
                this.RefreshLike(m_UserMoment.moment.likes);
        };
        moment.onCommentsRefresh = RefreshCommentCount;
    }

    public void OnClickOperate()
    {
        GameDebug.Log("CommunityItem->OnClickOperate");
    }

    public void OnClickIcon()
    {
        long userId = this.m_UserMoment.userId;
        RequestServerController.instance.RequestUserMomentInfo(userId, (userMomentsInfo) =>
        {
            var ump = GetComponentInParent<UIController>().ShowUI<UserHomePanel>();
            ump.Init(userMomentsInfo);
        });
    }

    void Update()
    {
        if(Time.frameCount % 300 == 0)
        {
            RefreshTime();
        }
    }

}
